package com.health.mapp.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.ImMsgNoticeExample;
import com.health.db.model.UserLIST;
import com.health.db.model.UserPreRegisterInfo;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.db.service.user.IUserPreRegisterInfoService;
import com.health.mapp.bean.GetSMSReq;
import com.health.mapp.bean.GetSMSResp;
import com.health.mapp.bean.Header;
import com.health.mapp.service.SecureUtil;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class GetSMSImpl implements ActionInterface {
	
	private IUserLISTService userLISTService  ;
	private ImMsgNoticeService imMsgNoticeService  ;
	private IUserPreRegisterInfoService userPreRegisterInfoService  ;
	private IStuffListService stuffListService;
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		// TODO Auto-generated method stub
		
		GetSMSReq request = (GetSMSReq) reqBean;
		GetSMSResp _resp = new GetSMSResp();
		
		String mobileNum = request.getUserPhone();	
		
		Date dt=new Date();
	    SimpleDateFormat matter1=new SimpleDateFormat("yyyy-MM-dd");
		
	    String remoteIP=SecureUtil.getRemoteHost((HttpServletRequest) header.getHttpRequest());
	    ImMsgNoticeExample example = new ImMsgNoticeExample();
	    example.setIp(remoteIP);
	    example.setUuId(matter1.format(dt)+"_"+header.getUuId());
	    example.setSign(matter1.format(dt)+"_"+header.getSign());
	    
	    int count= imMsgNoticeService.countNotice(example);
	    
	    if (!imMsgNoticeService.checkNotice(example)) {
	    	_resp.setErrorCode(-1);
	    	_resp.setErrorMsg("发送成功");
	    	return _resp;
		}
	    
	 //   Object redisCount = PushDataTemplateFactory.getInstanse().get(mobileNum+matter1.format(dt));
		
		//private String channel ; // 1注册          不传重置密码
		String channel = "0";
			
		if (StringUtils.isNotBlank(request.getChannel())) {
			channel = request.getChannel();
		}
		
		if (StringUtils.isBlank(mobileNum)) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}
		
	    String radom = String.valueOf(Math.round(Math.random()*900000+100000));
		TaobaoClient clients = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23312748", "d7badcea8b88c4560868f1a4e3c246c9");
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend(radom); 
		req.setSmsType("normal");
		req.setSmsFreeSignName("首儿健康汇");
		req.setSmsParamString("{\"code\":\" "+radom +"\",\"product\":\"首儿健康汇\"}");
		req.setRecNum(mobileNum);
		if (StringUtils.isNotBlank(channel)&&("1".equals(channel)||"2".equals(channel))) {
			
			
			UserLIST user=userLISTService.selectByUserNo(mobileNum);
			
			if (user!=null) {
			
				Short isExportFlag = user.getIsExportFlag();
				if (null!=isExportFlag&&1==isExportFlag.intValue()) {
					
				}else{
				
				_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS);
				_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_NAME_IS_EXISTS_NOTE);
				return _resp;
				
				}
			}else
			{
				if ("2".equals(channel))
				{
					//获取账号激活码
					UserPreRegisterInfo userPreRegisterInfo=userPreRegisterInfoService.getByUserNo(mobileNum);
					if (null==userPreRegisterInfo)
					{
						_resp.setErrorCode(-1);
						_resp.setErrorMsg("注册信息不存在");

						return _resp;
					}
				}
			}
			req.setSmsTemplateCode("SMS_5053413");
		}else if (StringUtils.isNotBlank(channel)&&("9".equals(channel))) {
			//微信绑定校验
			UserLIST user=userLISTService.selectByUserNo(mobileNum);
			if (user==null) {
				_resp.setErrorCode(-1);
				_resp.setErrorMsg("注册信息不存在");
				return _resp;
			}
			req.setSmsTemplateCode("SMS_5053416");
		}else{
			
			UserLIST user=userLISTService.selectByUserNo(mobileNum);
			
		
			
			if (user==null) {
				
				StuffDetailDto stuffDetail = stuffListService.selectByStuffNo(mobileNum);
				
				if (null==stuffDetail) {
					_resp.setErrorCode(ResultCode.LOGIN_FAIL_NAME_ERROR);
					_resp.setErrorMsg(ResultCode.LOGIN_FAIL_NAME_ERROR_NOTE);
					return _resp;
				}else{
					//req.setSmsFreeSignName("首儿医生");
					//req.setSmsParamString("{\"code\":\" "+radom +"\",\"product\":\"首儿医生\"}");
					
				}
			}
			req.setSmsTemplateCode("SMS_5053411");
		}
		
		AlibabaAliqinFcSmsNumSendResponse rsp;
		try {
			rsp = clients.execute(req);
			String response =rsp.getBody();
			  JSONObject jsStr = JSONObject.fromObject(response);
			  JSONObject errorResponse =  JSONObject.fromObject( jsStr.get("error_response"));
			  
			  if (null!=errorResponse&&(!"null".equals(errorResponse.toString()))) {
					_resp.setErrorCode(-1);
			    	_resp.setErrorMsg("发送失败请稍后重试");
			    	return _resp;
			   }
			  JSONObject resultStr =JSONObject.fromObject( jsStr.get("alibaba_aliqin_fc_sms_num_send_response"));
			  JSONObject reStr    =JSONObject.fromObject( resultStr.get("result"));
			  int errid = Integer.parseInt((String) reStr.get("err_code"));
			  
			  if (String.valueOf("0").equals((String) reStr.get("err_code")))
			    {
			    	_resp.setSms(radom);
			    }
			    else
			    {
			    	_resp.setErrorCode(-1);
			    	_resp.setErrorMsg("发送失败请稍后重试");
			    }
		} catch (ApiException e) {
			_resp.setErrorCode(-1);
			_resp.setErrorMsg("发送失败请稍后重试");
		}
		
		ImMsgNoticeExample notice = new ImMsgNoticeExample();
		notice.setRandom(radom);
		notice.setNoticeReceiveAddress(mobileNum);
		notice.setSendReceiveFlag(Short.valueOf(channel));
		notice.setIsUsedFlag((short) 1);
		notice.setCreateDate(DateUtils.now());
		notice.setModetypeid(Integer.valueOf(channel));
		notice.setUuId(matter1.format(dt)+"_"+header.getUuId());
		notice.setSign(matter1.format(dt)+"_"+header.getUuId());
		imMsgNoticeService.insert(notice);
		
		return _resp;
	}
	

	/**
	 * @return the userLISTService
	 */
	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	/**
	 * @param userLISTService the userLISTService to set
	 */
	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}


	/**
	 * @return the imMsgNoticeService
	 */
	public ImMsgNoticeService getImMsgNoticeService() {
		return imMsgNoticeService;
	}

	/**
	 * @param imMsgNoticeService the imMsgNoticeService to set
	 */
	public void setImMsgNoticeService(ImMsgNoticeService imMsgNoticeService) {
		this.imMsgNoticeService = imMsgNoticeService;
	}


	public IStuffListService getStuffListService() {
		return stuffListService;
	}


	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}


	public IUserPreRegisterInfoService getUserPreRegisterInfoService() {
		return userPreRegisterInfoService;
	}


	public void setUserPreRegisterInfoService(
			IUserPreRegisterInfoService userPreRegisterInfoService) {
		this.userPreRegisterInfoService = userPreRegisterInfoService;
	}
	
	
	
}
